/*var upload = null;
layui.use(['upload'], function(){
    upload = layui.upload;
    //console.log(upload+"=====upload");
    //initCreateUpload(0);
});*/

var addFormHtml = $("#zuankong").html();
// 钻孔数组集合
var arrayPile = [];
// 请求数据集
var ajaxData = {};
var requestData = {};

var drillImg0 = "";
var drillImg1 = "";
var drillImg2 = "";
$(document).ready(function () {
    //initDefaultSelect();


    // 添加钻孔信息
    $(".btn-add").click(function(){
        var size = $(".zuankong").length;
        var next = size;
        if (next == 10) {
            layer.msg('至多添加十个钻孔信息', {icon: 5});
            return;
        }
        var appendHtml = '<div class="zuankong" id="zuankong">' +
            '                                    <img class="del-zhuan" onclick="deleteZuan(this)" src="img/icon/oxp-remove.png" style="width: 30px;">' +
            '                                    <div class="layui-form-item form_item_align_left">' +
            '                                        <div class="layui-inline">' +
            '                                            <label class="layui-form-label">钻孔编号</label>' +
            '                                            <div class="layui-input-inline">' +
            '                                                <input type="hidden" value="null" name="id" class="layui-input" >' +
            '                                                <input type="text" name="drilling_no" lay-verify="required|number" autocomplete="off" class="layui-input" >' +
            '                                            </div>' +
            '                                        </div>' +
            '                                        <div class="layui-inline">' +
            '                                            <label class="layui-form-label">开孔日期</label>'+
            '                                            <div class="layui-input-inline">' +
            '                                                <input type="text" class="layui-input" name="open_drilling_time" placeholder="yyyy-MM-dd" id="openTime'+(next)+'">' +
            '                                            </div>' +
            '                                        </div>' +
            '                                        <div class="layui-inline">' +
            '                                            <label class="layui-form-label">钻机编号</label>' +
            '                                            <div class="layui-input-inline">' +
            '                                                <input type="text" name="rig_no" lay-verify="required|number" autocomplete="off" class="layui-input">' +
            '                                            </div>' +
            '                                        </div>' +
            '                                        <div class="layui-inline">' +
            '                                            <label class="layui-form-label">终孔深度</label>' +
            '                                            <div class="layui-input-inline">' +
            '                                                <input type="text" name="end_hole_depth" lay-verify="required|number" autocomplete="off" class="layui-input">' +
            '                                            </div>' +
            '                                        </div>' +
            '                                        <div class="layui-inline">' +
            '                                            <label class="layui-form-label">终孔日期</label>'+
            '                                            <div class="layui-input-inline">' +
            '                                                <input type="text" class="layui-input" name="close_drilling_time" placeholder="yyyy-MM-dd" id="closeTime'+(next)+'">' +
            '                                            </div>' +
            '                                        </div>' +

            '                                        <div class="layui-form-item form_item_align_left">' +
            '                                        <div class="layui-inline">' +
            '                                           <label class="layui-form-label">桩长(m)</label>' +
            '                                           <div class="layui-input-inline">' +
            '                                               <input type="number" name="a_actual_pile_length" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">' +
            '                                           </div>' +
            '                                        </div>' +
            '                                       <div class="layui-inline">' +
            '                                           <label class="layui-form-label">混凝土芯样长度(m)</label>' +
            '                                           <div class="layui-input-inline">' +
            '                                               <input type="number" name="concrete_length" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">'+
            '                                           </div>' +
            '                                       </div>'+
            '                                       <div class="layui-inline">' +
            '                                       <label class="layui-form-label">桩身混凝土采取率(%)</label>' +
            '                                       <div class="layui-input-inline">' +
            '                                               <input type="number" name="pile_concrete_yield" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">' +
            '                                           </div>' +
            '                                       </div>' +
            '                                       <div class="layui-inline">' +
            '                                           <label class="layui-form-label">沉渣厚度(mm)</label>' +
            '                                           <div class="layui-input-inline">' +
            '                                               <input type="number" name="sediment_thickness" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">' +
            '                                           </div>' +
            '                                       </div>' +
            '                                       </div>' +
            '                                       <div class="layui-form-item form_item_align_left">' +
            '                                       <div class="layui-inline">' +
            '                                           <label class="layui-form-label">持力层钻进深度(m)</label>' +
            '                                       <div class="layui-input-inline">' +
            '                                               <input type="number" name="drilling_depth_bearing_stratum" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">' +
            '                                           </div>' +
            '                                       </div>' +
            '                                       <div class="layui-inline">' +
            '                                           <label class="layui-form-label">持力层芯样长度(m)</label>' +
            '                                       <div class="layui-input-inline">' +
            '                                               <input type="number" name="bearing_core_length" lay-verify="required|number" placeholder="请填写数字" autocomplete="off" class="layui-input">' +
            '                                       </div>' +
            '                                       </div>' +
            '                                       <div class="layui-inline">' +
            '                                       <button type="button" class="layui-btn" index="0" id="test'+(next)+'">上传图片</button>' +
            '                                       <div class="layui-upload-list">' +
            '                                                <input type="hidden" value="" class="layui-input" name="drill_img"  id="drillImg'+(next)+'">' +
            '                                       <img class="layui-upload-img img-brower" style="max-height: 500px;" id="demo'+(next)+'">' +
            '                                       <p id="demoText'+(next)+'"></p>' +
            '                                       </div>' +
            '                                       </div>' +
            '                                       <div class="hr-line-dashed"></div>' +
            '                                       </div>' +
            '                                </div>';

        $("#content").append(appendHtml);
        initCreateUpload(next);

            layui.use('laydate', function(){
                var laydate = layui.laydate;
                laydate.render({
                    elem: ("#openTime"+(next))
                });
                laydate.render({
                    elem: ("#closeTime"+(next))
                });

            })

    });


    // 动态select事件
    $(document).on("click",".ow-select",function(){
        if ($(this).hasClass("layui-form-selected")) {
            $(this).removeClass("layui-form-selected");
        } else {
            $(this).addClass("layui-form-selected");
        }
    });

    $(document).on("click",".ow-select dl dd",function(){

        $(this).parent().find("dd[class=layui-this]").attr("class","");
        $(this).addClass("layui-this");
        var layValue = $(this).attr("lay-value");
        console.log(layValue+";;;;");
        $(this).parent().parent().find("input").val($(this).text())
        $(this).parent().parent().parent().find("option[selected='true']").attr("selected","false");
        $(this).parent().parent().parent().find("option[value="+layValue+"]").attr("selected","true");



    });

    // 添加完成请求后台
    $(".btn-sure").click(function () {
        arrayPile = [];
        // 获取基础桩信息
        var pid = $("#pid").val();
        var pile_number = $("#pile_number").val();
        var detection_unit = $("#detection_unit").val();
        var pile_region_id = $("#pile_region_id").val();
        if (isNULL(pile_number)) {
            layer.msg('桩号不能为空', {icon: 2});
            return;
        }
        var pile_diameter = $("#pile_diameter").val();
        if (isNULL(pile_diameter)) {
            layer.msg('桩径不能为空', {icon: 2});
            return;
        }
        // var concrete_strength = $("#concrete_strength").val();
        // if (isNULL(concrete_strength)) {
        //     layer.msg('混凝土强度不能为空', {icon: 2});
        //     return;
        // }
        var concrete_design_grade = $("#concrete_design_grade").val();
        if (isNULL(concrete_design_grade)) {
            layer.msg('设计等级不能为空', {icon: 2});
            return;
        }
        var c_pile_length = $("#c_pile_length").val();
        if (isNULL(c_pile_length)) {
            layer.msg('桩长不能为空', {icon: 2});
            return;
        }
        if (isNULL(pile_region_id)) {
            layer.msg('区域不能为空', {icon: 2});
            return;
        }
        var orifice_elevation = $("#orifice_elevation").val();
        var sediment_thickness_status = $("select[id='sediment_thickness_status']").val();
        var d_pile_integrity = $("select[id='d_pile_integrity']").val();
        var bearing_layer_status = $("select[id='bearing_layer_status']").val();
        // var description_pile_concrete_description = $("textarea[id=description_pile_concrete_description]").val();
        var p_pile_integrity = $("select[id='p_pile_integrity']").val();
        var casting_time = $("#casting_time").val();
        // var bearing_layer_description = $("textarea[id=bearing_layer_description]").val();
        var status = $("select[id='status']").val();

        ajaxData.id=pid;
        ajaxData.detectionUnit = detection_unit; //检测单位
        ajaxData.pileNumber = pile_number; //桩号
        ajaxData.cPileLength = c_pile_length; //施工方提供桩长(m)
        ajaxData.pileDiameter = pile_diameter; //桩径
        ajaxData.orificeElevation = orifice_elevation;//孔口高程
        ajaxData.concreteDesignGrade = concrete_design_grade;//混凝土设计强度等级，0：C20,1:C30,2:C40,3:C50,4:C60,5:C70,6:C80'
        ajaxData.pPileIntegrity =p_pile_integrity;//声波透射法检测桩身完整性类别
        ajaxData.castingTime =casting_time; //浇筑时间
        if (isNULL(casting_time)) {
            ajaxData.castingTime = timeStamp2String(new Date(), "ymdhms");
        }
        // ajaxData.concreteStrength = concrete_strength;//混泥土强度（MPa）
        ajaxData.sedimentThicknessStatus = sediment_thickness_status; //沉渣厚度是否满足设计要求
        ajaxData.dPileIntegrity = d_pile_integrity;//桩身完整性
        ajaxData.bearingLayerStatus =  bearing_layer_status; //持力层是否满足设计要求
        // ajaxData.descriptionPileConcreteDescription =description_pile_concrete_description;//桩身混泥土描述
        // ajaxData.bearingLayerDescription =bearing_layer_description;  //持力层描述
        ajaxData.status =status; //总体判定是否满足设计要求
        ajaxData.pileRegionId =pile_region_id; //区域

        // 获取钻孔信息
        $(".zuankong").each(function (index, e) {
            var pile_detail = {};
            var id = isNULL($(e).find("input[name=id]").val())?"":$(e).find("input[name=id]").val();
            var drilling_no = $(e).find("input[name=drilling_no]").val();
            var nowDate = new Date();
            var open_drilling_time = $(e).find("input[name=open_drilling_time]").val();
            if (isNULL(open_drilling_time)) {
                open_drilling_time = timeStamp2String(nowDate, "ymdhms")
            }
            var close_drilling_time = $(e).find("input[name=close_drilling_time]").val();
            if (isNULL(close_drilling_time)) {
                close_drilling_time = timeStamp2String(nowDate, "ymdhms")
            }
            var rig_no = $(e).find("input[name=rig_no]").val();
            var end_hole_depth = $(e).find("input[name=end_hole_depth]").val();
            var a_actual_pile_length = $(e).find("input[name=a_actual_pile_length]").val();
            var concrete_length = $(e).find("input[name=concrete_length]").val();
            var pile_concrete_yield = $(e).find("input[name=pile_concrete_yield]").val();
            var sediment_thickness = $(e).find("input[name=sediment_thickness]").val();
            var drilling_depth_bearing_stratum = $(e).find("input[name=drilling_depth_bearing_stratum]").val();
            var bearing_core_length = $(e).find("input[name=bearing_core_length]").val();
            var drill_img = isNULL($(e).find("input[name=drill_img]").val())?"":$(e).find("input[name=drill_img]").val();

            var concrete_strength = $(e).find("input[name=concrete_strength]").val();
            var description_pile_concrete_description = $(e).find("textarea[name=description_pile_concrete_description]").val();
            var bearing_layer_description = $(e).find("textarea[name=bearing_layer_description]").val();

            var updateIndex = $(e).find("button[type=button]").attr("index");

            pile_detail.id=id;
            pile_detail.pileId=pid;
            pile_detail.drillingNo = drilling_no;
            pile_detail.openDrillingTime = open_drilling_time;
            pile_detail.closeDrillingTime =close_drilling_time;
            pile_detail.rigNo = rig_no;
            pile_detail.endHoleDepth = end_hole_depth;
            pile_detail.aActualPileLength = a_actual_pile_length;
            pile_detail.concreteLength = concrete_length;
            pile_detail.pileConcreteYield = pile_concrete_yield;
            pile_detail.sedimentThickness = sediment_thickness;
            pile_detail.drillingDepthBearingStratum = drilling_depth_bearing_stratum;
            pile_detail.bearingCoreLength = bearing_core_length;

            pile_detail.concreteStrength = concrete_strength;
            pile_detail.descriptionPileConcreteDescription = description_pile_concrete_description;
            pile_detail.bearingLayerDescription = bearing_layer_description;



            /*console.log(updateIndex);
            if (0 == parseInt(updateIndex)) {
                console.log(drillImg0);
                pile_detail.drillImg = drillImg0;
            } else if(1 == parseInt(updateIndex)) {
                pile_detail.drillImg = drillImg1;
            } else if (2 == parseInt(updateIndex) ) {
                pile_detail.drillImg = drillImg2;
            }*/
            pile_detail.coreImgs =drill_img;
            arrayPile.push(pile_detail);
        });

        requestData.tPile = ajaxData;
        requestData.addDrillingParams = arrayPile;
        validateEachDrill(requestData);
    });


    // 图片预览
    $(".img-brower").click(function(){
        var imgSrc=$(this).attr('src');
        layer.open({
            type:1
            ,title:false
            ,closeBtn:0
            ,skin:'layui-layer-nobg'
            ,shadeClose:true
            ,content:'<img src="'+imgSrc+'" style="max-height:600px;max-width:100%;">'
            ,scrollbar:false
        })
    });

})

function initDefaultSelect() {
    var deterValue = $("select[name='determine']").val();
    console.log(deterValue);
}

// 删除钻孔信息
function deleteZuan(e) {
    layer.confirm('您确定要删除吗？删除后不可恢复', {
        btn: ['确定','取消'] //按钮
    }, function(){
        layer.close(layer.index);
        $(e).parent().remove();
    }, function(){
        layer.close(layer.index);
    });
}

/**
 * 校验每个钻孔信息是否为空
 * @param dataJson
 */
function validateEachDrill(dataJson) {
    console.log(dataJson);
    var pile_detail = dataJson.addDrillingParams;
    if (pile_detail == null || pile_detail == 0){
        layer.msg('请填写钻孔信息', {icon: 2});
        return;
    }
    for (var i = 0; i < pile_detail.length; i++) {
        if (isNULL(pile_detail[i].drillingNo)) {
            layer.msg('钻孔编号不能为空', {icon: 2});
            return;
        }
        if (isNULL(pile_detail[i].aActualPileLength)) {
            layer.msg('桩长不能为空', {icon: 2});
            return;
        }
        if (isNULL(pile_detail[i].endHoleDepth)) {
            layer.msg('终孔深度不能为空', {icon: 2});
            return;
        }
        if (isNULL(pile_detail[i].coreImgs)) {
            layer.msg('请上传图片', {icon: 2});
            return;
        }
    }
    requestAddPile(dataJson);
}

// 请求添加信息
function requestAddPile(dataJson) {
    console.log(dataJson);
    ajax({
        url: "pile/backGroundCreatePile",
        type: "POST",
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        data: JSON.stringify(dataJson),
        timeout: 10000,
        contentType: "application/json;charset=utf-8",
        error: function (xhr, type) {
            layer.msg("服务器异常，请稍后重试！", {time: 2000})
        },
        successx: function (data) {
            if (data.success == true) {
                layer.msg(data.message,{icon:1});
                setTimeout(function(){
                    window.location.href = "pilelist.html";
                    changeSubMenuActive("pilelist.html");
                },1800)
            } else {
                layer.msg(data.message,{time:1000})
            }
        },
    });

}


function laySelect(e) {
    if ($(e).hasClass("layui-form-selected")) {
        $(e).removeClass("layui-form-selected");
    } else {
        $(e).addClass("layui-form-selected");
    }
}


function initCreateUpload(num) {
    console.log(upload+"=====upload");
    console.log(num+"=======num");
    var leng = parseInt(num);
    var uploadInst0 = upload.render({
        elem: '#test'+leng
        ,url: web_url_prefix+'/upload/uploadImageMulit'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $("#demo"+leng+"").attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            if(res.success != "true"){
                return layer.msg('上传失败');
            }
            console.log(res.avatar+"============="+leng);
            //上传成功
            $("#drillImg"+(leng)).attr("value",res.avatar);
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText'+leng);
            demoText.html('<span style="color: #FF5722;">上传失败</span><a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst0.upload();
            });
        }
    });

    /*if (leng == 0) {
        var uploadInst0 = upload.render({
            elem: '#test'+leng
            ,url: web_url_prefix+'/upload/uploadImageMulit'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $("#demo"+leng+"").attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.success != "true"){
                    return layer.msg('上传失败');
                }
                //上传成功
                drillImg0 = res.avatar
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText'+leng);
                demoText.html('<span style="color: #FF5722;">上传失败</span><a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst0.upload();
                });
            }
        });
    } else if (leng == 1) {
        var uploadInst1 = upload.render({
            elem: '#test'+leng
            ,url: web_url_prefix+'/upload/uploadImageMulit'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $("#demo"+leng+"").attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                console.log(res);
                //如果上传失败
                if(res.success != "true"){
                    return layer.msg('上传失败');
                }
                //上传成功
                drillImg1 = res.avatar;
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText'+leng);
                demoText.html('<span style="color: #FF5722;">上传失败</span><a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst1.upload();
                });
            }
        });
    } else if (leng == 2) {
        var uploadInst2 = upload.render({
            elem: '#test'+leng
            ,url: web_url_prefix+'/upload/uploadImageMulit'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $("#demo"+leng+"").attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                console.log(res);
                //如果上传失败
                if(res.success != "true"){
                    return layer.msg('上传失败');
                }
                //上传成功
                drillImg2 = res.avatar;
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText'+leng);
                demoText.html('<span style="color: #FF5722;">上传失败</span><a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst2.upload();
                });
            }
        });
    }*/
}



function changeSubMenuActive(url) {

    // 获取父元素 操作
    $(window.parent.document).find("div[id=mainFrame]").parent().find("li[class=secNavActive]").attr("class", "");
    $(window.parent.document).find("div[id=mainFrame]").parent().find("li[resource_request_uri='"+url+"']").attr("class", "secNavActive");
}